package com.sinai.mshab.server;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

/**
 * Upload Servlet
 */
public class FileUploadServlet extends HttpServlet {

	final int UPLOAD_FILE_SIZE_LIMIT = 50000000; // 50 megs

	final int KEEP_IN_MEMORY = 256 * 1024;

	final String TEMP_FOLDER = "/tmp";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		// try the file upload.
		try {
			DiskFileUpload up = new DiskFileUpload();

			// 50 meg size limit, else FileUploadException is thrown
			up.setSizeMax(UPLOAD_FILE_SIZE_LIMIT);

			// maximum size that will be stored in memory
			up.setSizeThreshold(KEEP_IN_MEMORY);

			// the location for saving data that is larger than
			// getSizeThreshold()
			up.setRepositoryPath(TEMP_FOLDER);

			// parse multipart/form-data content
			List records = up.parseRequest(request);

			// getting the file
			FileItem theFile = (FileItem) records.get(0);

			System.out.println("The file that we will write is called: "
					+ theFile.getName());

			// use the /tmp directory and create a unique directory to avoid
			// overwrites when concurrently used.
			String path = "/tmp/" + (new Date()).getTime() + "/";

			// create the path, code curtusy of
			// http://www.roseindia.net/java/beginners/java-create-directory.shtml
			boolean success = (new File(path)).mkdir();

			// Runtime.getRuntime().exec("mkdir " + path);

			// sleep(1000);
			if (success) {
				System.out.println("Path created: " + path);
			}

			theFile.write(new File(path + theFile.getName()));

			System.out.println("Wrote the following file: " + path
					+ theFile.getName());

			// make sure everything is ok.
			File check = new File(path + theFile.getName());
			if (check == null || !check.exists()) {
				System.out.println("COULD NOT WRITE FILE TO SERVER!!!");
				return;
			}

			// now make a response with the file path and let
			// FileUploadComponent handle the rest.
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.println(path + theFile.getName());
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

	public static void sleep(int for_how_long) {
		try {
			Thread.sleep(for_how_long);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
